import {ref} from 'vue'
import {defineStore} from 'pinia'
import {httpKnowledgeCollects, httpCollectKnowledge} from '@/api/knowledge.js'

const useCollectStore = defineStore('collect', () => {
  const knowledgeCollects = ref([null])

  const getKnowledgeCollects = async () => {
    if (knowledgeCollects.value[0] === null) {
      const response = await httpKnowledgeCollects().catch(() => null)
      if (response) {
        const {list} = response
        knowledgeCollects.value = list
      }
    }
    return knowledgeCollects.value
  }

  /**
   * @param {int} kid
   * @returns {Promise<int|boolean>}
   */
  const collectKnowledge = async (kid) => {
    const response = await httpCollectKnowledge(kid).catch(() => null)
    if (!response) return false
    const {id, type} = response
    if (type === 1) {
      knowledgeCollects.value.push(id)
    } else {
      const index = knowledgeCollects.value.indexOf(id)
      if (index >= 0) {
        knowledgeCollects.value.splice(index, 1)
      }
    }
    return type
  }

  const isCollected = (id) => {
    return knowledgeCollects.value.indexOf(id) > -1
  }

  return {getKnowledgeCollects, collectKnowledge, isCollected}
})

export default useCollectStore